package org.blog.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.blog.beans.User;
import org.blog.logic.UserLogic;

/**
 * Servlet implementation class AdminServlet
 */
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		action(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		action(request, response);
	}
	
	private void action(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if("delete".equals(request.getParameter("do"))) {
			
			//TODO- nie dziala usuwanie
			int id = Integer.parseInt(request.getParameter("id"));
			if(!"admin".equals(UserLogic.getInstance().getUser(id).getLogin()))
				UserLogic.getInstance().delete(id);
		}
		ArrayList<User> users = (ArrayList<User>) UserLogic.getInstance().getUsers();
		request.setAttribute("users", users);
		
		
		getServletContext().getRequestDispatcher("/WEB-INF/jsp/adminPanel.jsp").forward(request, response);
	}

}
